# -*- coding: utf-8 -*-
"""
移动平均线多头排列分析报告生成器
"""
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import seaborn as sns

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def generate_analysis_report():
    """生成详细的分析报告"""
    
    # 读取数据
    try:
        all_stocks = pd.read_csv('bullish_stocks_all.csv')
        filtered_stocks = pd.read_csv('bullish_stocks_filtered.csv')
        
        print("=== 股票移动平均线多头排列分析报告 ===")
        print(f"分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print()
        
        # 基本统计
        print("1. 基本统计信息")
        print("-" * 50)
        print(f"总多头排列股票数量: {len(all_stocks)} 只")
        print(f"成交量过滤后数量: {len(filtered_stocks)} 只")
        print(f"过滤比例: {len(filtered_stocks)/len(all_stocks)*100:.1f}%")
        print()
        
        # 价格分析
        print("2. 价格分析")
        print("-" * 50)
        price_ranges = [
            (0, 10, "10元以下"),
            (10, 20, "10-20元"),
            (20, 50, "20-50元"),
            (50, 100, "50-100元"),
            (100, float('inf'), "100元以上")
        ]
        
        for min_price, max_price, label in price_ranges:
            count = len(all_stocks[(all_stocks['current_price'] >= min_price) & (all_stocks['current_price'] < max_price)])
            percentage = count / len(all_stocks) * 100
            print(f"{label}: {count} 只 ({percentage:.1f}%)")
        print()
        
        # 涨跌幅分析
        print("3. 涨跌幅分析")
        print("-" * 50)
        change_ranges = [
            (-float('inf'), -5, "跌幅超过5%"),
            (-5, 0, "小幅下跌"),
            (0, 5, "小幅上涨"),
            (5, 10, "涨幅5-10%"),
            (10, float('inf'), "涨幅超过10%")
        ]
        
        for min_change, max_change, label in change_ranges:
            count = len(all_stocks[(all_stocks['change_pct'] >= min_change) & (all_stocks['change_pct'] < max_change)])
            percentage = count / len(all_stocks) * 100
            print(f"{label}: {count} 只 ({percentage:.1f}%)")
        print()
        
        # 交易所分布
        print("4. 交易所分布")
        print("-" * 50)
        exchange_stats = all_stocks['exchange'].value_counts()
        for exchange, count in exchange_stats.items():
            percentage = count / len(all_stocks) * 100
            print(f"{exchange}: {count} 只 ({percentage:.1f}%)")
        print()
        
        # 成交量分析
        print("5. 成交量分析")
        print("-" * 50)
        volume_stats = all_stocks['volume'].describe()
        print(f"平均成交量: {volume_stats['mean']:,.0f} 股")
        print(f"中位数成交量: {volume_stats['50%']:,.0f} 股")
        print(f"最大成交量: {volume_stats['max']:,.0f} 股")
        print(f"最小成交量: {volume_stats['min']:,.0f} 股")
        print()
        
        # 移动平均线分析
        print("6. 移动平均线分析")
        print("-" * 50)
        ma5_stats = all_stocks['ma5'].describe()
        ma10_stats = all_stocks['ma10'].describe()
        ma20_stats = all_stocks['ma20'].describe()
        
        print("5日线统计:")
        print(f"  平均: {ma5_stats['mean']:.2f} 元")
        print(f"  中位数: {ma5_stats['50%']:.2f} 元")
        print(f"  最高: {ma5_stats['max']:.2f} 元")
        print(f"  最低: {ma5_stats['min']:.2f} 元")
        print()
        
        print("10日线统计:")
        print(f"  平均: {ma10_stats['mean']:.2f} 元")
        print(f"  中位数: {ma10_stats['50%']:.2f} 元")
        print(f"  最高: {ma10_stats['max']:.2f} 元")
        print(f"  最低: {ma10_stats['min']:.2f} 元")
        print()
        
        print("20日线统计:")
        print(f"  平均: {ma20_stats['mean']:.2f} 元")
        print(f"  中位数: {ma20_stats['50%']:.2f} 元")
        print(f"  最高: {ma20_stats['max']:.2f} 元")
        print(f"  最低: {ma20_stats['min']:.2f} 元")
        print()
        
        # 强势股票（涨幅超过5%）
        print("7. 强势股票（涨幅超过5%）")
        print("-" * 50)
        strong_stocks = all_stocks[all_stocks['change_pct'] > 5].sort_values('change_pct', ascending=False)
        if len(strong_stocks) > 0:
            print(f"共 {len(strong_stocks)} 只强势股票:")
            for _, stock in strong_stocks.head(10).iterrows():
                print(f"  {stock['stock_code']} {stock['stock_name']}: {stock['change_pct']:.2f}% (价格: {stock['current_price']:.2f}元)")
        else:
            print("无涨幅超过5%的股票")
        print()
        
        # 高价股票（价格超过50元）
        print("8. 高价股票（价格超过50元）")
        print("-" * 50)
        high_price_stocks = all_stocks[all_stocks['current_price'] > 50].sort_values('current_price', ascending=False)
        if len(high_price_stocks) > 0:
            print(f"共 {len(high_price_stocks)} 只高价股票:")
            for _, stock in high_price_stocks.head(10).iterrows():
                print(f"  {stock['stock_code']} {stock['stock_name']}: {stock['current_price']:.2f}元 (涨跌幅: {stock['change_pct']:.2f}%)")
        else:
            print("无价格超过50元的股票")
        print()
        
        # 成交量活跃股票
        print("9. 成交量活跃股票（成交量前10名）")
        print("-" * 50)
        active_stocks = all_stocks.nlargest(10, 'volume')
        for _, stock in active_stocks.iterrows():
            print(f"  {stock['stock_code']} {stock['stock_name']}: {stock['volume']:,}股 (价格: {stock['current_price']:.2f}元)")
        print()
        
        # 投资建议
        print("10. 投资建议")
        print("-" * 50)
        print("基于多头排列技术分析，建议关注以下类型的股票:")
        print("1. 涨幅适中（0-5%）且成交量活跃的股票")
        print("2. 价格在合理区间（10-50元）的优质股票")
        print("3. 5日线、10日线、20日线间距适中的股票")
        print("4. 注意风险控制，设置止损位")
        print()
        
        # 风险提示
        print("11. 风险提示")
        print("-" * 50)
        print("1. 技术分析仅供参考，不构成投资建议")
        print("2. 股市有风险，投资需谨慎")
        print("3. 建议结合基本面分析做出投资决策")
        print("4. 注意市场整体趋势和宏观经济环境")
        print("5. 建议分散投资，控制仓位")
        
    except FileNotFoundError as e:
        print(f"文件未找到: {e}")
        print("请先运行 analyze_ma_bullish_sql.py 生成数据文件")
    except Exception as e:
        print(f"生成报告时出错: {e}")

if __name__ == "__main__":
    generate_analysis_report()
